package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.*;
import com.zhangtai.modules.dto.AnnouncementDto;
import com.zhangtai.modules.dto.ParameterDto;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.system.AnnouncementEntity;
import com.zhangtai.modules.entity.system.BpmDataConfigurationEntity;
import com.zhangtai.modules.entity.system.CarouselEntity;
import com.zhangtai.modules.entity.system.ParameterEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.common.ImgUrlService;
import com.zhangtai.modules.service.system.AnnouncementService;
import com.zhangtai.modules.service.system.BpmDataConfigurationService;
import com.zhangtai.modules.service.system.CarouselService;
import com.zhangtai.modules.service.system.ParameterService;
import com.zhangtai.modules.vo.AnnouncementVo;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@RestController
@Api(tags="系统设置接口")
@RequestMapping("sysSetings")
@Slf4j
public class SystemSettingsController {
    @Autowired
    private LoginController loginController;
    @Autowired
    private BaseMssqlServiceImpl commonService;
    @Autowired
    private CarouselService carouselService;
    @Autowired
    private CarouselDao carouselDao;
    @Autowired
    private AnnouncementDao announcementDao;
    @Autowired
    private AnnouncementService announcementService;
    @Autowired
    private ParameterDao parameterDao;
    @Autowired
    private ParameterService parameterService;
    @Autowired
    private ImgUrlDao imgUrlDao;
    @Autowired
    private ImgUrlService imgUrlService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private BpmDataConfigurationService bpmDataConfigurationService;
    @Autowired
    private BpmDataConfigurationDao bpmDataConfigurationDao;

    @PostMapping("getBpmDataConfigurationPage")
    @ApiOperation(value="分页查询bpm流程参数配置")
    public R BpmDataConfigurationPage(@RequestParam( value = "jobSystemName",required = false) String jobSystemName,
                                      @RequestParam( value = "typeName",required = false) String typeName,
                                      @RequestParam( value = "bpmtypeId",required = false) String bpmtypeId,
                                      @RequestParam( value = "bpmtypeName",required = false) String bpmtypeName,
                                      @RequestParam( value = "createName",required = false) String createName,
                                    @RequestParam( value = "pageNum" ,defaultValue = "1") Integer pageNum,
                                    @RequestParam( value = "pageSize" ,defaultValue = "10") Integer pageSize) {

     PageResult  pageResult= bpmDataConfigurationService.queryPage(jobSystemName,typeName,bpmtypeId,bpmtypeName,createName,pageNum,pageSize);
        return R.ok(pageResult);
    }

    @PostMapping("getCarouselPage")
    @ApiOperation(value="分页查询轮播图")
    @PreAuthorize("hasAuthority('sys:admin:get')")
    public R getCarouselPage(@RequestParam( value = "bannerTitle",required = false) String bannerTitle,
                             @RequestParam( value = "pageNum" ,defaultValue = "1") Integer pageNum,
                             @RequestParam( value = "pageSize" ,defaultValue = "10") Integer pageSize) {

        PageResult  pageResult= carouselService.queryPage(bannerTitle,pageNum,pageSize);
        return R.ok(pageResult);
    }


    @PostMapping("getAnnouncementPage")
    @ApiOperation(value="分页查询公告")
//    @PreAuthorize("hasAuthority('sys:admin:get')")
    public R getAnnouncementPage(@RequestParam( value = "title",required = false) String title,
                                 @RequestParam( value = "subtitle",required = false) String subtitle,
                                 @RequestParam( value = "content",required = false) String content,
                                 @RequestParam( value = "type" ,defaultValue = "1") Integer type,
                             @RequestParam( value = "pageNum" ,defaultValue = "1") Integer pageNum,
                             @RequestParam( value = "pageSize" ,defaultValue = "10") Integer pageSize) {

        PageResult  pageResult= announcementService.queryPage(title,subtitle,content,type,pageNum,pageSize);
        List<AnnouncementEntity> announcementEntityList=pageResult.getList();
        List<AnnouncementDto> announcementDtoList=new ArrayList<>();
        for (AnnouncementEntity announcementEntity:announcementEntityList){
            AnnouncementDto announcementDto= BeanUtilsMabach.doToDto(announcementEntity,AnnouncementDto.class);
            List<String> fileUrlList=new ArrayList<>();
            if(!StringUtils.isEmpty(announcementEntity.getFileUrl())){
                  String[] UrlList=announcementEntity.getFileUrl().split(",");
                fileUrlList= Arrays.asList(UrlList);
            }
            announcementDto.setFileUrlList(fileUrlList);
            announcementDtoList.add(announcementDto);
        }
        pageResult.setList(announcementDtoList);
        return R.ok(pageResult);
    }

    @PostMapping("getParameterPage")
    @ApiOperation(value="分页查询通用参数")
    @PreAuthorize("hasAuthority('sys:admin:get')")
    public R getParameterPage(   @RequestParam( value = "name",required = false) String name,
                                 @RequestParam( value = "type",required = false) String type,
                                 @RequestParam( value = "pageNum" ,defaultValue = "1") Integer pageNum,
                                 @RequestParam( value = "pageSize" ,defaultValue = "10") Integer pageSize) {

        PageResult  pageResult= parameterService.queryPage(name,type,pageNum,pageSize);
        return R.ok(pageResult);
    }

    @PostMapping("getParameterList")
    @ApiOperation(value="根据type查询通用参数")
     public R getParameterPage( @RequestParam( value = "type") String type) {
        List<ParameterEntity>  parameterEntityList= parameterDao.selectList(new QueryWrapper<ParameterEntity>()
                .eq("type",type).eq("is_delete",0).orderByAsc("sort"));
        List<ParameterDto> parameterDtoList =new ArrayList<>();
        for (ParameterEntity parameterEntity:parameterEntityList){
            ParameterDto parameterDto= BeanUtilsMabach.doToDto(parameterEntity,ParameterDto.class);
            parameterDtoList.add(parameterDto);
        }
        return R.ok(parameterDtoList);
    }


    @PostMapping("/saveOrUpdateAnnouncement")
    @ApiOperation(value="保存/修改公告")
    @SysAuthorityLog(value = "保存/修改公告")
    @PreAuthorize("hasAuthority('sys:admin:update')")
    public R saveOrUpdateAnnouncement(@RequestBody AnnouncementVo announcementVo,HttpServletRequest request)throws Exception {
        JSONObject userInfo=  loginController.getUserInfo(request).getData();
        log.info("获取登录用户信息user:{}",userInfo);
        if (ObjectUtils.isEmpty(userInfo)) {
            return  R.error("请先登录");
        }
        R r;
        //保存附件
        EmployeeInfoEntity employeeInfoEntity=getEmployessInfoByCode(userInfo.getString("usercode"));
        AnnouncementEntity announcementEntity= BeanUtilsMabach.doToDto(announcementVo,AnnouncementEntity.class);
        ArrayList<String> fileUrlList=announcementVo.getFileUrlList();
        if(!CollectionUtils.isEmpty(fileUrlList)) {
            saveFile(employeeInfoEntity.getOid(), fileUrlList, "公告附件",12);
        }
        announcementEntity.setFileUrl(CollectionUtils.isEmpty(fileUrlList)?"":ListToString(fileUrlList));
        if(StringUtils.isEmpty(announcementVo.getId())){
            long id = snowflakeIdWorker.nextId();
            announcementEntity.setId(id);
            announcementEntity.setIsDelete(0);
            announcementEntity.setCreateTime(new Date());
            announcementEntity.setCreateCode(userInfo.getString("usercode"));
            announcementEntity.setCreateName(userInfo.getString("name"));
            r=announcementService.saveE(announcementEntity);
        }else{
            announcementEntity.setId(Long.valueOf(announcementVo.getId()));
            r= announcementService.updateByIdE(announcementEntity);
        }
        return r;
    }

    @PostMapping("/saveOrUpdateCarousel")
    @ApiOperation(value="保存/修改轮播图")
    @SysAuthorityLog(value = "保存/修改轮播图")
    @PreAuthorize("hasAuthority('sys:admin:update')")
    public R saveOrUpdateCarousel( @RequestParam( value = "id" ,required = false) String id,
                                         @RequestParam( value = "bannerTitle" ,required = false) String bannerTitle,
                                         @RequestParam(value = "bannerUrl") String bannerUrl,
                                         @RequestParam(value = "url",required = false) String url,
                                         @RequestParam(value = "remarks",required = false) String remarks,
                                         @RequestParam( value = "isShow" ,defaultValue = "1") Integer isShow,
                                         @RequestParam( value = "orderNum" ,required = false) Integer orderNum, HttpServletRequest request )throws Exception {
        JSONObject userInfo=  loginController.getUserInfo(request).getData();
        log.info("获取登录用户信息user:{}",userInfo);
        if (ObjectUtils.isEmpty(userInfo)) {
            return  R.error("请先登录");
        }
        R r;
        CarouselEntity carouselEntity=new CarouselEntity();
        carouselEntity.setBannerTitle(bannerTitle);
        carouselEntity.setBannerUrl(bannerUrl);
        carouselEntity.setUrl(url);
        carouselEntity.setIsShow(isShow);
        carouselEntity.setOrderNum(orderNum);
        carouselEntity.setRemarks(remarks);
        if(StringUtils.isEmpty(id)){
            carouselEntity.setIsDelete(0);
            carouselEntity.setCreateTime(new Date());
            carouselEntity.setCreateCode(userInfo.getString("usercode"));
            carouselEntity.setCreateName(userInfo.getString("name"));
            r=carouselService.saveE(carouselEntity);
        }else{
            carouselEntity.setId(Long.valueOf(id));
            r= carouselService.updateByIdE(carouselEntity);
        }
        return r;
    }

    @PostMapping("/saveOrUpdateParameter")
    @ApiOperation(value="保存/修改通用参数")
    @SysAuthorityLog(value = "保存/修改通用参数")
    @PreAuthorize("hasAuthority('sys:admin:update')")
    public R saveOrUpdateParameter( @RequestParam( value = "id" ,required = false) String id,
                                         @RequestParam( value = "name" ,required = false) String name,
                                         @RequestParam(value = "type",required = false) String type,
                                         @RequestParam(value = "value",required = false) String value,
                                         @RequestParam(value = "remarks",required = false) String remarks,
                                    @RequestParam(value = "sort",required = false) Integer sort,
                                HttpServletRequest request )throws Exception {
        JSONObject userInfo=  loginController.getUserInfo(request).getData();
        log.info("获取登录用户信息user:{}",userInfo);
        if (ObjectUtils.isEmpty(userInfo)) {
            return  R.error("请先登录");
        }
        R r;
        ParameterEntity parameterEntity=new ParameterEntity();
        parameterEntity.setName(name);
        parameterEntity.setType(type);
        parameterEntity.setValue(value);
        parameterEntity.setRemarks(remarks);
        parameterEntity.setSort(sort);
        if(StringUtils.isEmpty(id)){
            parameterEntity.setIsDelete(0);
            parameterEntity.setCreateTime(new Date());
            parameterEntity.setCreateCode(userInfo.getString("usercode"));
            parameterEntity.setCreateName(userInfo.getString("name"));
            r=parameterService.saveE(parameterEntity);
        }else{
            parameterEntity.setId(Long.valueOf(id));
            r= parameterService.updateByIdE(parameterEntity);
        }
        return r;
    }



    @PostMapping("/saveOrUpdateBpmDataConfiguration")
    @ApiOperation(value="保存/修改bpm流程参数配置")
    @SysAuthorityLog(value = "保存/修改bpm流程参数配置")
    public R saveOrUpdateBpmDataConfiguration( @RequestParam( value = "id" ,required = false) String id,
                                                     @RequestParam( value = "jobSystemId" ,required = false) Long jobSystemId,
                                                     @RequestParam(value = "jobSystemName",required = false) String jobSystemName,
                                                     @RequestParam(value = "typeId",required = false) Integer typeId,
                                                     @RequestParam(value = "typeName",required = false) String typeName,
                                                     @RequestParam(value = "bpmtypeId",required = false) String bpmtypeId,
                                                     @RequestParam(value = "bpmtypeName",required = false) String bpmtypeName,
                                                    @RequestParam(value = "isGroupId",required = false) String isGroupId,
                                    HttpServletRequest request )throws Exception {

        JSONObject userInfo=  loginController.getUserInfo(request).getData();
        log.info("获取登录用户信息user:{}",userInfo);
        if (ObjectUtils.isEmpty(userInfo)) {
            return  R.error("请先登录");
        }
        R r;
        BpmDataConfigurationEntity bpmDataConfigurationEntity=new BpmDataConfigurationEntity();
        bpmDataConfigurationEntity.setJobSystemId(jobSystemId);
        bpmDataConfigurationEntity.setJobSystemName(jobSystemName);
        bpmDataConfigurationEntity.setTypeId(typeId);
        bpmDataConfigurationEntity.setTypeName(typeName);
        bpmDataConfigurationEntity.setBpmtypeId(bpmtypeId);
        bpmDataConfigurationEntity.setBpmtypeName(bpmtypeName);
        bpmDataConfigurationEntity.setIsGroupId(isGroupId);
        if(StringUtils.isEmpty(id)){
            if(!ObjectUtils.isEmpty(jobSystemId)&&!ObjectUtils.isEmpty(typeId)){
                List<BpmDataConfigurationEntity> bpmDataConfigurationEntityList= bpmDataConfigurationDao.selectList(new QueryWrapper<BpmDataConfigurationEntity>()
                        .eq("job_system_id",jobSystemId).eq("type_Id",typeId));
                if (bpmDataConfigurationEntityList.size()>0){
                    return R.error(jobSystemName+ " 体系已配置业务类型为 "+ typeName+ " 的BPM参数，无需重复配置！");
                }
            }
            bpmDataConfigurationEntity.setIsDelete(0);
            bpmDataConfigurationEntity.setCreateTime(new Date());
            bpmDataConfigurationEntity.setCreateCode(userInfo.getString("usercode"));
            bpmDataConfigurationEntity.setCreateName(userInfo.getString("name"));
            r=bpmDataConfigurationService.saveE(bpmDataConfigurationEntity);
        }else{
            if(!ObjectUtils.isEmpty(jobSystemId)&&!ObjectUtils.isEmpty(typeId)){
                List<BpmDataConfigurationEntity> bpmDataConfigurationEntityList= bpmDataConfigurationDao.selectList(new QueryWrapper<BpmDataConfigurationEntity>()
                        .eq("job_system_id",jobSystemId).eq("type_Id",typeId).ne("id",id));
                if (bpmDataConfigurationEntityList.size()>0){
                    return R.error(jobSystemName+ " 体系已配置业务类型为 "+ typeName+ " 的BPM参数，无需重复配置！");
                }
            }
            bpmDataConfigurationEntity.setId(Long.valueOf(id));
            r= bpmDataConfigurationService.updateByIdE(bpmDataConfigurationEntity);
        }
        return r;
    }

    @DeleteMapping("/deleteBpmDataConfiguration")
    @ApiOperation(value="删除bpm流程参数配置")
    @SysAuthorityLog(value="删除bpm流程参数配置")
    public R deleteBpmDataConfiguration(@RequestParam(value = "id") String id)  {
        bpmDataConfigurationDao.deleteById(id);
        return R.ok();
    }


    @DeleteMapping("/deleteCarouselById")
    @ApiOperation(value="删除轮播图信息")
    @SysAuthorityLog(value="删除轮播图信息")
    @PreAuthorize("hasAuthority('sys:admin:update')")
    public R deleteUserBankCard(@RequestParam(value = "id") String id)  {
        carouselDao.deleteById(id);
        return R.ok();
    }

    @DeleteMapping("/deleteAnnouncementById")
    @ApiOperation(value="删除公告信息")
    @SysAuthorityLog(value="删除公告信息")
    @PreAuthorize("hasAuthority('sys:admin:update')")
    public R deleteAnnouncementById(@RequestParam(value = "id") String id)  {
        announcementDao.deleteById(id);
        imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("oid", id).eq("type", 12));
        return R.ok();
    }

    @DeleteMapping("/deleteParameterById")
    @ApiOperation(value="删除通用参数信息")
    @SysAuthorityLog(value="删除通用参数信息")
    @PreAuthorize("hasAuthority('sys:admin:update')")
    public R deleteParameterById(@RequestParam(value = "id") String id)  {
        parameterDao.deleteById(id);
        return R.ok();
    }

    public EmployeeInfoEntity getEmployessInfoByCode(String code) {
        List<EmployeeInfoEntity> employeeInfoEntitys = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("code", code).eq("is_delete", 0).orderByDesc("create_time"));
        if (!CollectionUtils.isEmpty(employeeInfoEntitys)) {
            return employeeInfoEntitys.get(0);
        }
        //        先去查询本地库，如果有则返回最新的那条
        EmployeeInfoEntity employeeInfoEntity = commonService.finEmpFromMssqlByCode(code);
        return employeeInfoEntity;
    }


    //附件保存
    public void saveFile(Long oid, ArrayList<String> fileList,String name,Integer type){
            for (String s : fileList) {
                imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("url", s).eq("type", type));
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setName(name);
                imgUrlEntity.setOid(oid);
                imgUrlEntity.setType(type);
                imgUrlEntity.setCreateTime(new Date());
                imgUrlEntity.setUrl(s);
                imgUrlService.saveE(imgUrlEntity);
            }

    }
    public String ListToString(ArrayList<String> fileUrlList){
        String Url="";
        for ( String s:fileUrlList){
            Url+=s+",";
        }
        return Url.substring(0,Url.length()-1);
    }
}
